/*
 * This file is part of b.AMP.
 *
 * b.AMP is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * b.AMP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with b.AMP.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __BAMP_EXCEPTION_HPP__
#define __BAMP_EXCEPTION_HPP__

#include <bamp/rc.h>
#include <exception>
#include <string>

namespace bamp
{

    /**
     * b.AMP generic exception class. The Exception class wraps an
     * integer return code in a C++ exception.
     */
    class Exception : public std::exception
    {
    public:

        /**
         * Initialize the exception using the corresponding return
         * code.
         * @param rc return code
         */
        explicit Exception(const bamp_rc rc) : m_rc(rc) {}
        virtual ~Exception() throw() {}

        /**
         * @return the return code held by this exception
         */
        bamp_rc rc() const
        {
            return m_rc;
        }

        /**
         * @return a human-readable description of the return code
         *         held by this exception
         */
        virtual const char* what() const throw()
        {
            return bamp_rc_to_string(m_rc);
        }


    private:
        bamp_rc m_rc;
    };
};


#define BAMP_RC_THROW(rc)                       \
    if (rc != BAMP_RC_OK)                       \
    {                                           \
        throw bamp::Exception(rc);              \
    }

#define BAMP_RC_CATCH(expr)                     \
    try                                         \
    {                                           \
        expr;                                   \
    }                                           \
    catch(const bamp::Exception& e)             \
    {                                           \
        return e.rc();                          \
    }

#define BAMP_ASSERT_THROW(cond, rc)             \
    if (!(cond))                                \
    {                                           \
        throw bamp::Exception(BAMP_RC_##rc);    \
    }

#define BAMP_THROW(rc)                          \
        throw bamp::Exception(BAMP_RC_##rc);

#endif // __BAMP_EXCEPTION_HPP__
